<template>
    <div class="home-container" v-if="now_pj">
        <div class="detail">
            <div class="left">
                <div style="font-weight: bold;font-size: 20px;">{{ now_pj.projectName }}</div>
                <hr />
                <div>by <span class="author-name" @click="visitProfile(now_pj.authorID,now_pj.authorName)">{{now_pj.authorName }}</span></div>
                <div>team: {{ now_pj.teamName||"personal yet" }}</div>
                <div>star: {{ now_pj.favorites }}</div>
                <div>{{ now_pj.createdAt }}</div>
                <div class="footer">
                    <a-button type="default" style="width:100px;font-size:16px;" @click="deploy"
                        :disabled="deployButtonState==='deploying'">
                        {{ deployButtonState==='noDeploy'?"deploy":deployButtonState==='deploying'?"deploying":"Redeploy" }}
                    </a-button>
                    <a-button type="default" style="width:100px;font-size:16px;" @click="chatDrawerOpen('large')" :disabled="deployButtonState!='deployed'">
                        chat
                    </a-button>
                    <a-button type="default" style="width:100px;font-size:16px;" @click="clonePj" :disabled="isclone">
                        {{ isclone?"forked":"clone" }}
                    </a-button>
                </div>
            </div>
            <div class="middle">
                <h4 style="font-size: 20px; font-weight: bold;">Description</h4>
                <hr />
                {{ now_pj.description }}
            </div>
        </div>
        <div class="view" v-if="now_pj && now_pj.projectID">
            <FlowCanvas :id="now_pj.projectID" :iscontrolable="false" />
        </div>
        <a-drawer :size="'large'" :width="850" :open="isDrawerOpen" @close="chatDrawerClose" :closable="false">    
            <Chat :projectID="now_pj.projectID" />
        </a-drawer>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, nextTick, onUnmounted } from 'vue';
import { useUserStore } from '../stores/userStore';
import { useRouter } from 'vue-router';
import { useServer } from '@/components/ts/useServer';
import { useProjectsStore } from '../stores/projectsStore';

import Icon from '../components/icons/Icon.vue'
import { formatDateTimeCN, dayjslib } from '../utils/DataTime.js';
import FlowCanvas from '@/components/FlowCanvas.vue';

import { message } from 'ant-design-vue';
import Chat from './ChatView.vue'
const { post,postWithCallback } = useServer();
const userStore = useUserStore();
const router = useRouter();
const projectsStore = useProjectsStore();

const now_pj = ref<any>(null)
let visitorID = <string>''
let visitorName = <string>''

const mockTestUrl='https://m1.apifoxmock.com/m1/6951272-6668040-default/api'
onMounted(async () => {
    userStore.isvisitor = true;
    await projectsStore.fetchAllProjects();

    let pjID = router.currentRoute.value.params.id as string
    visitorID = router.currentRoute.value.params.visitorID as string
    visitorName = router.currentRoute.value.params.visitorName as string
    let tmp=localStorage.getItem(pjID)
    if(tmp){
        now_pj.value = JSON.parse(tmp)    
    }else{
        console.log('localStorage item not found:',pjID)
    }
    // console.log("pjID:", pjID)
    // console.log("visitorID:", visitorID)
    // console.log("visitorName:", visitorName)
    // console.log("open now_pj:", now_pj.value)
    //userStore.login(visitorID, visitorName);
    let res1 = await post('remote_login', { userID: now_pj.value.authorID })
    if (!res1.success) {
        console.log("login failed")
        return
    } else {
        userStore.login(now_pj.value.authorID, now_pj.value.authorName);
        await projectsStore.initializeProjects();
        console.log("projects:", projectsStore.projects)
    }

})
onUnmounted(() => {
    localStorage.removeItem(pjID);
})
const visitProfile = (authorID: string,authorName: string) => {
    const routeUrl = router.resolve({
        name: 'Profile',
        params: { id: authorID,name:authorName,visitorID:visitorID,visitorName:visitorName }
    });
    window.open(routeUrl.href, '_blank');
}
const isclone=ref<boolean>(false)
const clonePj =  () => {
     projectsStore.addProject(now_pj.value.projectName, now_pj.value.description, now_pj.value.content, visitorID)
    message.success("clone success")
    isclone.value = true
}
//'noDeploy' 'deploying' 'deployed'
const deployButtonState =ref('noDeploy');
const deploy = async () => {

    if (deployButtonState.value === 'deploying') return;
    let res = await post('createWS', { userID: now_pj.value.authorID, currentProject: now_pj.value.projectID, content: now_pj.value.content })
    deployButtonState.value = 'deploying';
    if (res?.success) {
        deployButtonState.value = 'deployed';
    }else{
        console.log("deploy failed",res)
        deployButtonState.value = 'noDeploy';
    }
    setTimeout(() => { checkDeployed() }, 2000);
};
const checkDeployed = () => {
    
    postWithCallback('checkProjectRunning', { userID: now_pj.value.authorID, projectID: now_pj.value.projectID }, (response: any) => {
        console.log(response)
        if (response.running) {
            deployButtonState.value = "deployed";
        } else {
            deployButtonState.value = "noDeploy";
        }
    })

}
import type { DrawerProps } from 'ant-design-vue';
const isDrawerOpen = ref<boolean>(false);

const chatDrawerOpen = (val: DrawerProps['size']) => {
  isDrawerOpen.value = true;
};

const chatDrawerClose = () => {
  isDrawerOpen.value = false;
};
</script>

<style scoped lang="scss">
.home-container {
    height: 100%;
    width: 100%;
    position: relative;
    overflow-y: auto;
    padding: 20px;
    background: radial-gradient(circle at center,
            rgba(173, 216, 230, 0)20%,
            rgba(142, 201, 220, 0.3) 80%,
            rgba(110, 197, 225, 0.684) 100%);
}

.view {
    height: 80%;
    width: 100%;
    background: #fff;
}
.detail {
    padding: 10px;
    margin-bottom: 5px;
    height: 190px;
    width: 100%;
    background: #d2c2c200;
    border-radius: 10px;
    border: 1px solid #65c1da;
    box-shadow: 0px 0px 10px 0px rgba(101, 193, 218, 0.5);
    display: flex;

    .left {
        flex: 2;

        .footer {
            display: flex;
            padding:5px;
            justify-content: space-around;
            align-items: center;
        }

        .author-name {
            font-weight: bold;
            font-size: 18px;

            &:hover {
                color: #65c1da;
                cursor: pointer;
            }
        }
    }

    .middle {
        padding: 0 15px;
        overflow-x: hidden;
        overflow-y: auto;
        flex: 4;
        border-left: 1px solid #65c1da;
        border-right: 1px solid #65c1da;
    }


}
</style>
